<?php
namespace App\Http\Middleware;

use App\Models\Menu;
use Closure;
use Auth;
use Illuminate\Support\Facades\Route;

class AuthenticateWithAdmin
{

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		// 检查是否登录。
		if (Auth::admin()->guest()) {
			if ($request->ajax() || $request->wantsJson()) {
				return response('Unauthorized.', 401);
			} else {
				return redirect()->guest(route('AdminLogin'));
			}
		}

		// 检查权限。
 		$user = Auth::admin()->user();
 		// ID1的为超级管理员，拥有所有权限。
 		if ($user->username !== 'root') {
            $menus = Menu::whereIn('id',$user->menus)->get();
            $menus_arr = [];
            foreach ($menus as $key=>$item){
                $menus_arr[] = $item->route;
            }
 			if (! in_array($request->route()->getName(), $menus_arr)) {
 				if ($request->ajax() || $request->wantsJson()) {
 					return response('Forbidden.', 403);
 				} else {
 					return response()->view('admin.errors.403', [], 403);
 				}
 			}
 		}

		return $next($request);
	}
}
